//
//  检查报告->肝炎病毒
//  yilutongxing
//
//  Created by T&J on 2017/6/26.
//  Copyright © 2017年 YZE. All rights reserved.
//
#import "CommonDefine.h"
#import "IQActionSheetPickerView.h"
#import "IQActionSheetViewController.h"
#import "HepatitisViewController.h"
#import "ViralInflectionViewCell.h"
#import "YZEUI_ToggleButton.h"

@interface HepatitisViewController () <UITableViewDelegate, UITableViewDataSource, IQActionSheetViewControllerDelegate, IQActionSheetPickerViewDelegate>
@property(nonatomic,strong) NSIndexPath *tempIndexPath;
@property(nonatomic,strong) NSArray *sectionTitleArr;//节标题
@property(nonatomic,strong) NSArray *rowTitleArr;//行标题
@property(strong,nonatomic) NSArray *propertyNameArr;//模型属性数组
@property(strong,nonatomic) NSMutableArray *cellArr;//缓存生成的cell
@property(strong,nonatomic) NSArray *PNArr;//阴阳性选择列表
@property(strong,nonatomic) NSMutableArray *cellPnArr;//每行值的定量/定性
@property(nonatomic,strong) NSMutableArray *btnArr;//阴阳按钮数组
@property(nonatomic,strong) NSMutableArray *tfArr;//定量输入框数组
@property (strong, nonatomic) IBOutlet UITableView *detailTableview;

@property (strong, nonatomic) RPHepatitisModel *blood;//血液标本
@property (assign, nonatomic) BOOL isBloodShow;//当前展示的数据类型,真为血液，假为尿液
@property (strong, nonatomic) RPHepatitisModel *curShow;//当前展示的数据
@end

@implementation HepatitisViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"肝炎病毒";
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackGroundImage"]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存"
                                                                             style:UIBarButtonItemStyleDone
                                                                            target:self
                                                                            action:@selector(saveAction)];
    UIImage *img = [[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:img
                                                                            style:UIBarButtonItemStyleDone
                                                                           target:self
                                                                           action:@selector(backAction)];
    [_detailTableview registerNib:[UINib nibWithNibName:@"ViralInflectionViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"vtcell"];
    
    self.detailTableview.delegate = self;
    self.detailTableview.dataSource = self;
    
    self.sectionTitleArr = @[@"乙肝病毒", @"丙肝病毒"];
    self.rowTitleArr = @[
                         @[@"乙肝表面抗原", @"乙肝表面抗体", @"乙肝e抗原", @"乙肝e抗体", @"乙肝核心抗体", @"乙肝病毒DNA"],
                         @[@"丙型肝炎抗体", @"丙型肝炎病毒RNA"]
                         ];
    self.cellPnArr = [NSMutableArray array];
    self.propertyNameArr = @[
                             @[@"hepatitis1", @"hepatitis2", @"hepatitis3", @"hepatitis4", @"hepatitis5", @"hepatitis6"],
                             @[@"hepatitis7", @"hepatitis8"]
                             ];
    
    self.cellArr = [NSMutableArray array];
    if (_data) {
        _blood = [RPHepatitisModel initFromSuperBean1:_data];
    }
    else {
        _blood = [RPHepatitisModel new];
        _data = [RPHepatitisBean new];
    }
    self.isBloodShow = YES;
    self.curShow = _blood;//默认显示血液标本数据
    [self setPAofAllcell];
}

- (void)viewWillAppear:(BOOL)animated{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件响应
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveAction{
    [self saveData];
    
    if ([self.delegate respondsToSelector:@selector(backHepatitisData:)]) {
        [self.delegate backHepatitisData:_data];
    }
    
    [self backAction];
}

//定性按钮响应
- (void)OnPNBtnClick:(YZEUI_ToggleButton*)sender{
    ViralInflectionViewCell *cell = (ViralInflectionViewCell*)[[sender superview] superview];
    NSString *val;
    if (sender.selected) {
        val = @"阳性";
    }
    else {
        val = @"阴性";
    }
    if (_isBloodShow) {
        [_blood setValue:val forKey:cell.accessibilityIdentifier];
    }
    else {
        
    }
}

- (void)OnTextfieldTextChanged:(UITextField*)tf{
    UIView *cell = (UIView*)[[tf superview] superview];
    if (_isBloodShow) {
        [_blood setValue:tf.text forKey:cell.accessibilityIdentifier];
    }
    else {
        
    }
}

#pragma mark - 业务逻辑
//设置所有cell的阴阳性or定量
- (void)setPAofAllcell{
    [_cellPnArr removeAllObjects];
    NSInteger rowIndex;
    NSString *val;
    for (int i=0; i<_sectionTitleArr.count; i++) {
        NSArray *rowArr = _rowTitleArr[i];
        NSArray *propertyArr = _propertyNameArr[i];
        NSMutableArray *pnArr = [NSMutableArray array];
        for (int j=0; j<rowArr.count*2+1; j++) {
            if (j%2==0 && j!=0) {
                rowIndex = j/2-1;
                rowIndex = rowIndex>0?rowIndex:0;
                val = [_curShow valueForKey:propertyArr[rowIndex]];
                BOOL p;
                if (!val) {
                    p = NO;
                }
                else {
                    NSRange rg = [val rangeOfString:@"性"];
                    p = !(rg.location==NSNotFound);
                }
                
                [pnArr insertObject:[NSNumber numberWithBool:p] atIndex:rowIndex];
            }
        }
        [_cellPnArr addObject:pnArr];
    }
}

//把bean存入model
- (void)saveData{
    self.data = [self.blood pushData2Superbean1:self.data];
    //self.data = [self.urinis pushData2Superbean2:self.data];
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 10)];
    header.backgroundColor = COLOR(243, 243, 243);
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _sectionTitleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *rowArr = _rowTitleArr[section];
    return rowArr.count*2+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row%2==0 && indexPath.row!=0) {
        ViralInflectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"vtcell"];
        if (!cell) {
            cell = [[ViralInflectionViewCell alloc]init];
        }
        [((UIButton*)[cell viewWithTag:1]) addTarget:self action:@selector(OnPNBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.amountTF addTarget:self action:@selector(OnTextfieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.tag = ROWINDEX(indexPath);
        NSInteger rowIndex = indexPath.row/2-1;
        rowIndex = rowIndex>0?rowIndex:0;
        NSArray *titles = _propertyNameArr[indexPath.section];
        NSString *key = titles[rowIndex];
        NSString *val = [_curShow valueForKey:key];
        NSArray *pns = _cellPnArr[indexPath.section];
        NSNumber *ispa = pns[rowIndex];
        ((ViralInflectionViewCell*)cell).isP = [ispa boolValue];
        [((ViralInflectionViewCell*)cell) giveVal:val];
        ((ViralInflectionViewCell*)cell).accessibilityIdentifier = key;
        
        //缓存cell
        if (_cellArr.count<indexPath.section+1) {
            [_cellArr addObject:[NSMutableArray array]];
        }
        if (((NSMutableArray*)_cellArr[indexPath.section]).count<titles.count) {
            [((NSMutableArray*)_cellArr[indexPath.section]) addObject:cell];
        }
        
        return cell;
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        if (indexPath.row==0) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            UIEdgeInsets inset = cell.separatorInset;
            inset.left = 0;
            cell.separatorInset = inset;
            cell.textLabel.text = _sectionTitleArr[indexPath.section];
        }
        else {
            NSInteger rowIndex = (indexPath.row-1)/2;
            NSArray *titles = _rowTitleArr[indexPath.section];
            cell.textLabel.text = titles[rowIndex];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row%2!=0 && indexPath.row!=0) {
        IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" viewDelegate:self controllerDelegate:self];
        picker.titleFont = [UIFont systemFontOfSize:12];
        picker.titleColor = [UIColor redColor];
        [picker setTitlesForComponents:@[self.PNArr]];
        picker.tag = ROWINDEX(indexPath);
        [picker show];
    }
}

#pragma mark - 数据配置
- (NSArray*)PNArr{
    if (!_PNArr) {
        _PNArr = @[@"定性", @"定量"];
    }
    return _PNArr;
}

- (void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray<NSString *> *)titles{
    NSIndexPath *currentIndexPath = DEROWINDEX(pickerView.tag);
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row+1 inSection:currentIndexPath.section];
    NSInteger rowIndex = nextIndexPath.row/2-1;
    rowIndex = rowIndex>0?rowIndex:0;
    NSString *valstr = [titles componentsJoinedByString:@""];
    if ([valstr isEqualToString:@"定性"]) {
        [self.cellPnArr[nextIndexPath.section] replaceObjectAtIndex:rowIndex withObject:[NSNumber numberWithBool:YES]];
        //预设置默认值，否则若未点击按钮则无法响应事件从而设置阴阳性值
        UITableViewCell *cell = [self.detailTableview cellForRowAtIndexPath:nextIndexPath];
        if (_isBloodShow) {
            [_blood setValue:@"阴性" forKey:cell.accessibilityIdentifier];
        }
        else {
            //[_urinis setValue:@"阴性" forKey:cell.accessibilityIdentifier];
        }
    }
    else {
        [self.cellPnArr[nextIndexPath.section] replaceObjectAtIndex:rowIndex withObject:[NSNumber numberWithBool:NO]];
    }
    [self.detailTableview reloadData];
}

- (void)didDismissPickerView:(IQActionSheetPickerView *)pickerView{
    
}

@end
